﻿using CommandLinex;
using N_m3u8DL_RE.Entity;
using N_m3u8DL_RE.Enums;
using System.Text.Json;

namespace N_m3u8DL_RE.CommandLinex
{
    public class MuxOptionsValueProcessor : ICommandLineValueProcessor
    {
        /// <summary>
        /// 从Json字符串值处理请求头信息将其转换为字典形式。
        /// </summary>
        /// <param name="value"></param>
        /// <param name="targetType"></param>
        /// <returns></returns>
        public object Process(string value, Type targetType)
        {
            if (string.IsNullOrEmpty(value))
                return null;
            var v = value;
            var p = new ComplexParamParser(v);
            // 混流格式
            var format = p.GetValue("format") ?? v.Split(':')[0]; // 若未获取到，直接:前的字符串作为format解析
            var parseResult = System.Enum.TryParse(format.ToUpperInvariant(), out MuxFormat muxFormat);
            if (!parseResult)
            {
                throw new Exception($"format={format} not valid");
            }
            // 混流器
            var muxer = p.GetValue("muxer") ?? "ffmpeg";
            if (muxer != "ffmpeg" && muxer != "mkvmerge")
            {
                throw new Exception($"muxer={muxer} not valid");
            }
            // 混流器路径
            var bin_path = p.GetValue("bin_path") ?? "auto";
            if (string.IsNullOrEmpty(bin_path))
            {
                throw new Exception($"bin_path={bin_path} not valid");
            }
            // 是否删除
            var keep = p.GetValue("keep") ?? "false";
            if (keep != "true" && keep != "false")
            {
                throw new Exception($"keep={keep} not valid");
            }
            // 是否忽略字幕
            var skipSub = p.GetValue("skip_sub") ?? "false";
            if (skipSub != "true" && skipSub != "false")
            {
                throw new Exception($"skip_sub={keep} not valid");
            }
            // 冲突检测
            if (muxer == "mkvmerge" && format == "mp4")
            {
                throw new Exception($"mkvmerge can not do mp4");
            }
            return new MuxOptions()
            {
                UseMkvmerge = muxer == "mkvmerge",
                MuxFormat = muxFormat,
                KeepFiles = keep == "true",
                SkipSubtitle = skipSub == "true",
                BinPath = bin_path == "auto" ? null : bin_path
            };
        }
    }
}
